﻿using System;
using System.Windows;
using TVideo.Cef;
using TVideo.Util;

namespace TVideo
{
    /// <summary>
    /// PlayWindow.xaml 的交互逻辑
    /// </summary>
    public partial class PlayWindow
    {
        private string _url;
        private string _sourceName;
        public PlayWindow(string url)
        {
            _url = url;
            _sourceName = PlaySourceUtil.GetDefaultName();

            InitializeComponent();

            InitBrowser();

            Loaded += PlayWindow_Loaded;
        }

        private void PlayWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Start(Url);
        }

        public string Url
        {
            get { return _url; }
            set { _url = value; }
        }

        public string SourceName
        {
            get { return _sourceName; }
            set
            {
                _sourceName = value;

            }
        }

        private void InitBrowser()
        {
            WebBrowser.MenuHandler = new CefMenuHandler();
            WebBrowser.KeyboardHandler = new CefKeyBoardHandler();
            WebBrowser.LifeSpanHandler = new CefLifeSpanHandler();

            WebBrowser.StartNewWindow += WebBrowser_StartNewWindow;
        }

        private void WebBrowser_StartNewWindow(object? sender, NewWindowEventArgs e)
        {
            //Start(e.Url);
        }

        private void Start(string? url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            if (string.IsNullOrEmpty(_sourceName))
            {
                return;
            }

            var playSource = PlaySourceUtil.GetByName(_sourceName);
            if (playSource == null)
            {
                return;
            }

            if (url.StartsWith(Constant.BlankString))
            {
                return;
            }

            try
            {
                string playUrl = $"{playSource.Url}?url={url}";

                WebBrowser.Load(playUrl);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());
            }
        }
    }
}
